package com.ljz.controller;

import com.github.pagehelper.PageInfo;
import com.ljz.entity.Role;
import com.ljz.entity.User;
import com.ljz.service.RoleService;
import com.ljz.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;


@Controller
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;

    @RequestMapping("/login")
    public String index(Model model,String username,String password) {
        if (userService.login(username, password)) {
            model.addAttribute("username", username);
            return "index";
        } else
            return "login";
    }
    @RequestMapping("/userInfo")
    public String userInfo(Model model,String username,Integer currentPage,Integer pageSize) {
        if (currentPage == null || currentPage < 1){
            currentPage = 1;
        }
        if (pageSize == null || pageSize < 1){
            pageSize = 5;
        }
        if (username==null){
            username="";
        }
        System.out.println(username+"-----------------------");
        PageInfo<User> users = userService.findUsers(username, currentPage, pageSize);
        model.addAttribute("users", users);
        return "userInfo";
    }
    @RequestMapping("/register")
    @ResponseBody
    public String register(@RequestBody User user) {
        if (user.getUsername()==null || user.getPassword()==null ||user.getRole()==null) {
            return "register";
        } else {
            if (userService.register(user)) {
                return "true";
            }
            return "false";
        }
    }
    @RequestMapping("/toregister")
    public String toRegister(Model model) {
        List<Role> roles = roleService.getRoles();
        model.addAttribute("roles", roles);
        return "register";
    }
    @RequestMapping("/deleteUser")
    public String deleteUser(Integer id) {
        List<Integer> list = new ArrayList<>();
        list.add(id);
        userService.deleteUsers(list);
        return "redirect:/userInfo";
    }
}
